/**
 ****************************************************************************
 * Copyright (C) Marcelo F. Ochoa. All rights reserved.                      *
 * ------------------------------------------------------------------------- *
 * This software is published under the terms of the Apache Software License *
 * version 1.1, a copy of which has been included  with this distribution in *
 * the LICENSE file.                                                         *
 */

package org.apache.cocoon.util;

import java.sql.SQLException;
import java.util.Hashtable;

import org.apache.regexp.RE;
import org.apache.regexp.RESyntaxException;

/**
 * This class is a helper class for HSQLDB Database to provide Regular expresion
 * matching function.
 * @author <a href="mailto:mochoa@ieee.org">Marcelo F. Ochoa</a>
 * @version 1.0
 * @see org.hsqldb.Library
 *   for aditional HSQLDB Library functions
 * @see org.apache.regexp.RE
 *   for Regular Expresion valid syntax
 */
public class HSQLDBLibrary {
    /** hastable used to cache Regular expresions */
    private static Hashtable cachedExpresions = new Hashtable();

    /*
     * Expresion matching function
     * Returns 1 if match 0 otherwhise
     * Usage:
     *   select * from esi_pages where RegMatch('^/cms/.*$',source)=1
     *   where source is a column name of the table esi_pages
     * Note:
     *   Register this function using:
     *   grant all on class 'org.apache.cocoon.util.HSQLDBLibrary' to public
     *   create alias RegMatch FOR 'org.apache.cocoon.util.HSQLDBLibrary.REMatch
     */
    public static int REMatch(String regExp, String value) throws SQLException {
      RE pattern = (RE)cachedExpresions.get(regExp);
      if (pattern==null) {
        try {
          pattern = new RE(regExp);
          cachedExpresions.put(regExp,pattern);
        } catch (RESyntaxException se) {
          throw new SQLException("RegMatch: Failed to compile the pattern, "+se.getLocalizedMessage());
        }
      }
      return (pattern.match(value)) ? 1 : 0;
    }
} 